package com.lock.immersive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lock.immersive.exception.BusinessException;
import com.lock.immersive.manager.CosManager;
import com.lock.immersive.mapper.ProductItemMapper;
import com.lock.immersive.mapper.ProductMapper;
import com.lock.immersive.mapper.UserMapper;
import com.lock.immersive.pojo.domain.Product;
import com.lock.immersive.pojo.domain.ProductItem;
import com.lock.immersive.pojo.domain.Tuan;
import com.lock.immersive.pojo.domain.User;
import com.lock.immersive.pojo.dto.ProductCondition;
import com.lock.immersive.pojo.dto.ProductDto;
import com.lock.immersive.pojo.dto.ProductItemDto;
import com.lock.immersive.pojo.vo.ProductPriceVo;
import com.lock.immersive.service.ProductService;
import com.lock.immersive.utils.ErrorCode;
import com.lock.immersive.utils.JWT;
import com.lock.immersive.utils.ResponseApi;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author zhao
 * @description 针对表【product】的数据库操作Service实现
 * @createDate 2023-07-02 00:04:03
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements ProductService {
    @Resource
    public ProductMapper productMapper;
    @Resource
    public ProductItemMapper productItemMapper;
    @Resource
    public UserMapper userMapper;
    @Resource
    public CosManager cosManager;

    @Override
    public ResponseApi<Object> insertProduct(ProductDto productDto, HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = JWT.getTokenId(token);
        User user = userMapper.selectById(userId);
        Integer merchantId = user.getMerchantId();
        System.out.println(productDto.getPicList());
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        product.setMerchantId(merchantId);
        System.out.println(product);
        int insert = productMapper.insert(product);
        if (insert > 0) {
            return ResponseApi.success();
        } else {
            throw new BusinessException(ErrorCode.INSERT_ERROR);
        }
    }

    @Override
    public ResponseApi<Object> insertProductItem(ProductItemDto productItemDto) {
        ProductItem productItem = new ProductItem();
        BeanUtils.copyProperties(productItemDto, productItem);
        int insert = productItemMapper.insert(productItem);
        if (insert > 0) {
            return ResponseApi.success();
        } else {
            throw new BusinessException(ErrorCode.INSERT_ERROR);
        }
    }

    @Override
    public Page<Product> getProductList(ProductCondition condition) {
        Page<Product> listPage = new Page<>();
        Long current = condition.getCurrent();
        Long size = condition.getSize();
        ProductCondition.Type type = condition.getType();
        QueryWrapper<Product> qw = new QueryWrapper<>();
        if (type == ProductCondition.Type.count) {
            qw.orderByDesc("buy_count");
        } else if (type == ProductCondition.Type.view) {
            qw.orderByDesc("view_count");
        } else {
            qw.orderByDesc("create_time");
        }
        Page<Product> productPage = productMapper.selectPage(new Page<Product>(current, size), qw);

        productPage.getRecords().forEach(item -> {
            Integer productId = item.getProductId();
            List<ProductItem> productItemByProductId = productItemMapper.getProductItemByProductId(productId);
            ProductPriceVo productPrice = productItemMapper.getProductPrice(productId);
            if (productPrice != null) {
                if (!productPrice.getMinPrice().equals(productPrice.getMaxPrice())) {
                    item.setPrice(productPrice.getMinPrice() + " - " + productPrice.getMaxPrice());
                } else {
                    item.setPrice(String.valueOf(productPrice.getMinPrice()));
                }
            }

            item.setProductItemList(productItemByProductId);
            Tuan tuan = productMapper.getTuanByProductId(productId);
            item.setTuan(tuan);

        });
        return productPage;
    }

    @Override
    public ResponseApi<List<ProductItem>> getProductItemList(Integer productId) {
        List<ProductItem> productItemByProductId = productItemMapper.getProductItemByProductId(productId);
        return ResponseApi.success(productItemByProductId);
    }

    @Override
    public ResponseApi<Object> updateProduct(Product product) {
        int i = productMapper.updateById(product);
        if (i >= 0) {
            return ResponseApi.success();
        } else {
            throw new BusinessException(ErrorCode.UPDATE_ERROR);
        }
    }

    @Override
    public ResponseApi<Object> updateProductItem(ProductItem productItem) {
        int i = productItemMapper.updateById(productItem);
        if (i >= 0) {
            return ResponseApi.success();
        } else {
            throw new BusinessException(ErrorCode.UPDATE_ERROR);
        }
    }

    @Override
    public ResponseApi<Object> deleteProductList(List<String> ids) {
        int i = productMapper.deleteBatchIds(ids);
        if (i > 0) {
            List<Integer> itemIds = new ArrayList<>();
            ids.forEach(productId ->{
                List<Integer> itemList = productItemMapper.selectList(new QueryWrapper<ProductItem>().eq("product_id", productId)).stream().map(ProductItem::getItemId).collect(Collectors.toList());
                if(itemList.size() > 0){
                   deleteProductItem(itemList);
                }
            });
            return ResponseApi.success();
        }
        else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    public int deleteProductItem(List<Integer> ids) {
        return productItemMapper.deleteBatchIds(ids);
    }
}




